import Vue from 'vue';
import App from './App.vue';
import router from './utils/router';
import store from './utils/store';
import './utils/registerServiceWorker';
import storage from "./utils/storage";
import ElementUI from 'element-ui';
import NProgress from 'nprogress' // Progress 进度条
import Moment from 'moment';



import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css'// Progress 进度条样式
import '@/assets/css/main.less';
import '@/assets/css/reset.less';
Vue.use(ElementUI);

Vue.config.productionTip = false;
Vue.prototype.$store = store;
Vue.prototype.$storage = storage;
Vue.prototype.moment = Moment;

router.beforeEach((to, from, next) => {
    NProgress.start();//开启进度条
    //其他端，管理后台PC端的逻辑
    if (to.meta.title) document.title = '览汉缘智能管理系统-'+to.meta.title;//动态化每个页面的标题
    const whiteList = ['Login'];
    const token = storage.get('token');
    if(token){
        //如果令牌存在，不能直接访问登录界面
        if(to.matched.some( m => m.meta.login)){
            next({name:'Main'});
        }else{
            //动态路由只挂载一次
            if(store.getters.routers.length){
                next();
            }else{
                store.dispatch('generateRoutes').then(()=>{
                    router.addRoutes(store.getters.routers); // 动态添加可访问路由表
                    next({ ...to });//hack方法 确保addRoutes已完成
                });
            }
        }
    }else{
        //登录白名单，在执行next({name:'Login'})的时候允许进入该页面
        if(whiteList.includes(to.name)){
            next();
        }else{
            next({name:'Login'});// token不存在的情况全部重定向到登录页
        }
    }
});

NProgress.configure({ showSpinner: false });//取消右上角的进度环
router.afterEach((transition) => {
    NProgress.done();//关闭进度条
});

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');
